import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Edit,
  Clock,
  Users,
  Shield,
  MoreHorizontal,
  Trash2,
  Package, // Added Package for materials
  Wrench, // For equipment
  Truck, // For vehicles
  GitBranch, // For versioning
  Sparkles, // For AI upgrade
  Copy,
} from "lucide-react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";

const scenarioLabels = {
  highway: "高速公路",
  roadsOrdinary: "普通公路(封路)",
  electricPowerCircuit: "电力线路(停电)",
  powerLinesWithoutPowerOutage: "电力线路(不停电)",
  railwayOrdinary: "普通铁路",
  riverWay: "通航河流",
  others: "其他",
};

export default function MethodTemplateCard({
  template = {},
  onEdit,
  onCopy,
  onDelete,
  onEnhance,
  isEnhancing,
}) {
  const getMethodIcon = (methodCode) => {
    const icons = {
      helicopterStringing: "🚁",
      droneStringing: "🛸",
      rocketStringing: "🚀",
      cableCraneStringing: "🏗️",
      scaffoldingErection: "🏗️",
      manualStringing: "👷",
    };
    return icons[methodCode] || "⚙️";
  };

  const safeSteps = Array.isArray(template.constructionSteps)
    ? template.constructionSteps
    : [];
  const complexity = safeSteps.length;

  // 汇总各类资源数量
  const materialCount = safeSteps.reduce(
    (sum, step) =>
      sum +
      (Array.isArray(step.requiredMaterials)
        ? step.requiredMaterials.length
        : 0),
    0
  );
  const personnelCount = safeSteps.reduce(
    (sum, step) =>
      sum +
      (Array.isArray(step.requiredPersonnel)
        ? step.requiredPersonnel.length
        : 0),
    0
  );
  const equipmentCount = safeSteps.reduce(
    (sum, step) =>
      sum +
      (Array.isArray(step.requiredEquipment)
        ? step.requiredEquipment.length
        : 0),
    0
  );
  const vehicleCount = safeSteps.reduce(
    (sum, step) =>
      sum +
      (Array.isArray(step.requiredVehicles) ? step.requiredVehicles.length : 0),
    0
  );
  const safetyMeasureCount = safeSteps.reduce(
    (sum, step) =>
      sum +
      (Array.isArray(step.safetyMeasures) ? step.safetyMeasures.length : 0),
    0
  );
  const qualityMeasureCount = safeSteps.reduce(
    (sum, step) =>
      sum +
      (Array.isArray(step.qualityMeasures) ? step.qualityMeasures.length : 0),
    0
  );

  const getComplexityConfig = (count) => {
    if (count <= 3)
      return { label: "简单", color: "bg-green-100 text-green-700" };
    if (count <= 7)
      return { label: "中等", color: "bg-yellow-100 text-yellow-700" };
    return { label: "复杂", color: "bg-red-100 text-red-700" };
  };

  const complexityConfig = getComplexityConfig(complexity);

  const handleEdit = (e) => {
    e.stopPropagation();
    if (onEdit && typeof onEdit === "function") {
      onEdit(template);
    }
  };
  const handleCopy = (e) => {
    e.stopPropagation();
    if (onCopy && typeof onCopy === "function") {
      onCopy(template);
    }
  };
  const handleDelete = () => {
    if (onDelete && typeof onDelete === "function") {
      onDelete(template.id);
    }
  };

  const handleEnhance = () => {
    if (onEnhance && typeof onEnhance === "function") {
      onEnhance(template.id);
    }
  };

  return (
    <Card className="group hover:shadow-xl transition-all duration-300 border-0 shadow-lg bg-white flex flex-col">
      <CardHeader className="pb-4">
        <div className="flex items-start justify-between">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 bg-blue-100 rounded-xl flex items-center justify-center text-xl">
              {getMethodIcon(template.methodCode)}
            </div>
            <div>
              <CardTitle
                className="text-lg font-bold text-gray-900 cursor-pointer hover:text-blue-600"
                onClick={(e) => {
                  e.stopPropagation();
                  handleEdit(e);
                }}
              >
                {template.methodName || "未命名模板"}
              </CardTitle>
              {/* <div className="flex items-center gap-2 mt-1">
                <Badge variant="secondary">v{template.version || "1.0"}</Badge>
                <p className="text-sm text-gray-500">
                  代码: {template.methodCode || "N/A"}
                </p>
              </div> */}
            </div>
          </div>

          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button
                variant="ghost"
                size="icon"
                className="opacity-0 group-hover:opacity-100 transition-opacity"
              >
                <MoreHorizontal className="w-4 h-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              {/* <DropdownMenuItem onClick={handleEnhance} disabled={isEnhancing}>
                <Sparkles className="w-4 h-4 mr-2 text-blue-500" />
                AI升级版本
              </DropdownMenuItem> */}
              <DropdownMenuItem onClick={handleEdit}>
                <Edit className="w-4 h-4 mr-2" />
                编辑
              </DropdownMenuItem>
              <DropdownMenuItem onClick={handleCopy}>
                <Copy className="w-4 h-4 mr-2" />
                复制
              </DropdownMenuItem>
              <DropdownMenuSeparator />
              <DropdownMenuItem onClick={handleDelete} className="text-red-600">
                <Trash2 className="w-4 h-4 mr-2" />
                删除
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </CardHeader>

      <CardContent className="space-y-4 flex-grow flex flex-col">
        <p className="text-sm text-gray-600 line-clamp-2 h-10">
          {template.description || "暂无描述"}
        </p>

        {template.changeLog && (
          <div className="text-xs p-2 bg-blue-50/50 rounded-md border border-blue-100 text-blue-700">
            <div className="font-medium flex items-center gap-1.5 mb-1">
              <GitBranch className="w-3.5 h-3.5" />
              版本说明:
            </div>
            <p className="line-clamp-2">{template.changeLog}</p>
          </div>
        )}

        <div className="grid grid-cols-2 gap-3 pt-4 border-t mt-auto">
          <div className="flex items-center gap-2 text-sm text-gray-600">
            <Clock className="w-4 h-4" />
            <span>{complexity} 个步骤</span>
          </div>
          <div className="flex items-center gap-2 text-sm text-gray-600">
            <Package className="w-4 h-4" />
            <span>{materialCount} 项物料</span>
          </div>
          <div className="flex items-center gap-2 text-sm text-gray-600">
            <Users className="w-4 h-4" />
            <span>{personnelCount} 个工种</span>
          </div>
          <div className="flex items-center gap-2 text-sm text-gray-600">
            <Wrench className="w-4 h-4" />
            <span>{equipmentCount} 项工器具</span>
          </div>
          <div className="flex items-center gap-2 text-sm text-gray-600">
            <Truck className="w-4 h-4" />
            <span>{vehicleCount} 类车辆</span>
          </div>
          <div className="flex items-center gap-2 text-sm text-gray-600">
            <Shield className="w-4 h-4" />
            <span>{safetyMeasureCount} 项安全措施</span>
          </div>
        </div>

        <div className="flex flex-wrap gap-2">
          <Badge className={complexityConfig.color}>
            {complexityConfig.label}
          </Badge>
          {Array.isArray(template.applicableScenarios) &&
            template.applicableScenarios.slice(0, 2).map((scenario, index) => (
              <Badge key={index} variant="outline" className="text-xs">
                {scenarioLabels[scenario] || scenario}
              </Badge>
            ))}
        </div>
      </CardContent>
    </Card>
  );
}
